//
//  ZPlayerCache.swift
//  ZPlayer
//
//  Created by zuber on 2018/11/15.
//  Copyright © 2018年 zuber. All rights reserved.
//

import Foundation
import AVFoundation

class ZPlayerCache {
  
  static let shared = ZPlayerCache()
  private var diskDocumentPath: String
  private let cacheName = "im.zuber.zplayer.cache"
  private lazy var fileManager = FileManager()
  private init(){
    let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    diskDocumentPath = ((paths.first ?? "") as NSString).appendingPathComponent(cacheName)
    //先创建好对象的文件夹
    do {
      try self.fileManager.createDirectory(atPath: self.diskDocumentPath, withIntermediateDirectories: true, attributes: nil)
    } catch _ {}
  }
  
  // 缓存文件
  func save(_ asset: AVAsset,forKey key: String,complete: (()->())? = nil) {
    let mixComposition = AVMutableComposition()
    guard let videoTrack = asset.tracks(withMediaType: .video).first , let audioTrackFirst = asset.tracks(withMediaType: .audio).first else  { return }
    
    let firstTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
    try? firstTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: asset.duration) , of: videoTrack, at: .zero)
    let audioTrack = mixComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
    try? audioTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: asset.duration), of: audioTrackFirst, at: .zero)
    
    let exportSession = AVAssetExportSession.init(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
    let path = self.path(for: key)
    exportSession?.outputURL = URL(fileURLWithPath: path)
    // 是否对网络进行优化
    exportSession?.shouldOptimizeForNetworkUse = true
    // 转换成MP4格式
    exportSession?.outputFileType = AVFileType.mp4
    exportSession?.exportAsynchronously(completionHandler: {
      print("缓存成功")
      guard let status = exportSession?.status else { return }
      switch status {
      case .completed:
        print("completed")
      case .exporting:
        print("exporting")
      case .failed,.cancelled,.unknown :
        print("failed")
      case .waiting:
        print("waiting")
      }
      print(exportSession?.error.debugDescription ?? "")
      complete?()
    })
  }
  
  func get(_ key: String ) -> URL? {
    let path = self.path(for: key)
    if self.fileManager.fileExists(atPath: path){
      let url = URL(fileURLWithPath: path)
      return url
    }
    return nil
  }
  
  private func path(for key: String) -> String{
    return (diskDocumentPath as NSString).appendingPathComponent("\(key.zz_MD5).mp4")
  }
  
}

